package com.donger.web.admin.controller.upms;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.donger.auth.component.UserDetail;
import com.donger.auth.utils.SecurityUtil;
import com.donger.business.entity.UserDto;
import com.donger.business.entity.UserInfo;
import com.donger.business.modules.upms.dto.UserForm;
import com.donger.business.modules.upms.entity.SysUser;
import com.donger.business.modules.upms.service.ISysUserService;
import com.donger.business.modules.upms.vo.UserVo;
import com.donger.common.core.utils.Res;
import com.donger.common.core.utils.Result;
import com.donger.common.web.annotation.AutoLog;
import com.donger.common.web.baseweb.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 * 系统用户 前端控制器 基本完成
 * </p>
 * <p>
 * 用户表增加 别名 user
 */
@AllArgsConstructor
@RestController
@RequestMapping("/sys/user")
@Api(tags = "系统用户管理")
public class SysUserController extends BaseController {

    private static final String MODULE_NAME = "系统用户管理";
    private static final Long SUPER_ADMIN = 1L;
    private final ISysUserService sysUserService;

    /**
     * 所有用户列表
     */
    @GetMapping("/list")
    @ApiOperation(notes = "分页查询用户", value = "")
//    @DictMethod
    @AutoLog(moduleName = MODULE_NAME, value = "查询用户")
    public Result list(Page<UserVo> page, SysUser sysUser) {
        return Res.ok(sysUserService.getUserWithRolePage(page, Wrappers.<SysUser>lambdaQuery()
                .like(StrUtil.isNotBlank(sysUser.getUsername()),SysUser::getUsername,sysUser.getUsername())
                .eq(StrUtil.isNotBlank(sysUser.getStatus()),SysUser::getStatus,sysUser.getStatus())
        ));
    }

    /**
     * 获取登录的用户信息  用户登陆
     */
    @GetMapping("/info")
    public Result<UserInfo> info() {
        Long currentUserId = SecurityUtil.getUser().getUserId();
        SysUser user = sysUserService.getById(currentUserId);
        return Res.ok(sysUserService.findUserInfo(user));
    }


    /**
     * 用户信息
     */
    @GetMapping("/info/{userId}")
    public Result<UserInfo> info(@PathVariable("userId") Long userId) {
        SysUser user = sysUserService.getById(userId);
        //获取用户所属的角色列表
        UserInfo userInfo = sysUserService.findUserInfo(user);
        return Res.ok(userInfo);
    }

    /**
     * 保存用户
     */
    @PostMapping("/save")
    @AutoLog(moduleName = MODULE_NAME, value = "保存用户")
    @PreAuthorize("@pms.hasPermission('sys:user:save')")
    public Result<Boolean> save(@RequestBody UserDto user) {
        return Res.ok(sysUserService.saveUser(user));
    }

    /**
     * 修改用户
     */
    @PostMapping("/update")
    @PreAuthorize("@pms.hasPermission('sys:user:update')")
    @AutoLog(moduleName = MODULE_NAME, value = "更新用户")
    public Result<Boolean> update(@RequestBody UserDto user) {
        return Res.ok(sysUserService.updateUserById(user));
    }

    /**
     * 删除用户
     */
    @GetMapping("/delete/{userId}")
    @PreAuthorize("@pms.hasPermission('sys:user:del')")
    @AutoLog(moduleName = MODULE_NAME, value = "删除用户")
    public Result<Boolean> delete(@PathVariable("userId") Long userId) {
        Long currentUserId = SecurityUtil.getUser().getUserId();
        if (userId.equals(SUPER_ADMIN)) {
            return Res.error("不能删除管理员");
        }
        if (userId.equals(currentUserId)) {
            return Res.error("当前用户不能删除");
        }
        return Res.ok(sysUserService.deleteUserById(userId));
    }


    /**
     *
     * @param userForm
     * @return
     */
    @PostMapping("/edit")
    @ApiOperation(value = "用户信息个人信息")
    @AutoLog(moduleName = MODULE_NAME, value = "修改个人信息")
    public Result edit(@RequestBody UserForm userForm) {
        UserDetail userDetail = SecurityUtil.getUser();
        SysUser temp = new SysUser();
        temp.setUserId(userDetail.getUserId());
        temp.setPhone(userForm.getPhone());
        temp.setUsername(userForm.getUsername());
        sysUserService.update(temp, new LambdaUpdateWrapper<SysUser>().eq(SysUser::getUserId, userDetail.getUserId()));
        return Res.ok();
    }

    /**
     * 修改用户头像
     * @return
     */
    @PutMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam("url") String url){
        Long userId = SecurityUtil.getUser().getUserId();
        sysUserService.update(new LambdaUpdateWrapper<SysUser>()
                .set(SysUser::getAvatar,url)
                .eq(SysUser::getUserId,userId)
        );
        return Res.ok("更新成功");
    }

    /**
     * 更新当前用户密码
     * @param userForm
     * @return
     */
    @PutMapping("/updatePassowrd")
    public Result updatePassword(@RequestBody UserForm userForm){
        Long userId = SecurityUtil.getUser().getUserId();
        sysUserService.updatePassword(userId,userForm.getPassword(),userForm.getNewpass());
        return Res.ok("修改成功");
    }

    /**
     * 查询当前鞥路账户绑定情况
     * @return
     */
    @GetMapping("/binding")
    public Result listBind(){

        Long userId = SecurityUtil.getUser().getUserId();
        SysUser user = sysUserService.getById(userId);

        Map<String,Boolean> map = MapUtil.newHashMap();
        // 码云是否绑定
        map.put("gitee",StrUtil.isNotBlank(user.getGiteeLogin()));
        // 微信是否绑定
        map.put("wechat",StrUtil.isNotBlank(user.getWxOpenid()));
        // 钉钉是否绑定
        map.put("ding",StrUtil.isNotBlank(user.getDingId()));
        return Res.ok(map);
    }

}

